import { Effect, Reducer } from 'umi';

import { getWidgetRecords, getDashboards, saveWidgetRecord
} from '@/services/selfquery';

import { WidgetsItem } from '../type';

export interface IndexLibraryModelState {
  widgetRecords: Array<number>;
  widgets: Array<WidgetsItem>;
  projectId: number;
}

export interface IndexLibraryModelType {
  namespace: 'indexLibrary';
  state: IndexLibraryModelState;
  effects: {
    fetchDashboards: Effect;
    fetchInitWidgetRecords: Effect;
    fetchUpdateProjectId: Effect;
    fetchUpdateWidgetRecords: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const IndexLibraryModel: IndexLibraryModelType = {
  namespace: 'indexLibrary',

  state: {
    projectId: 0, // 项目ID，用做限制查询
    widgets: [], // 所有指标列表
    widgetRecords: [], // 感兴趣的指标
  },

  effects: {
    // 获取所有的指标列表
    *fetchDashboards({ payload }: any, { call, put }: any) {
      const response = yield call(getDashboards, payload);
      yield put({
        type: 'save',
        payload: { widgets: response.payload },
      });
    },

    //获取项目ID
    *fetchUpdateProjectId({ payload }: any, { put }: any) {
      yield put({
        type: 'save',
        payload: { projectId: payload },
      });
    },

    // 记录感兴趣指标
    *fetchUpdateWidgetRecords({payload}: any, { call, put }: any) {
      yield call(saveWidgetRecord, {records: JSON.stringify(payload)});
      yield put({
        type: 'save',
        payload: { widgetRecords: payload }
      });
    },
    
    // 获取感兴趣的指标
    *fetchInitWidgetRecords({ payload }: any, { call, put }: any) {
      const response = yield call(getWidgetRecords, payload);
      const widgetRecords = response.payload;
      const datas = !widgetRecords ? [] : JSON.parse(widgetRecords);
      yield put({
        type: 'save',
        payload: { widgetRecords: datas },
      });
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default IndexLibraryModel;
